/*
 * FormCurso.java
 *
 * Created on 16 de Novembro de 2008, 12:41
 */
package br.com.radaction.gui;

import br.com.radaction.DAO.CursoDAO;
import br.com.radaction.DTO.Curso;
import java.sql.SQLException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

/**
 *  Esta Classe é uma implementação GUI para mostrar os cursos cadastrados pelo aluno
 * @author  robson
 */
public class FormCurso extends javax.swing.JInternalFrame {

    JFrame mdi;

    /** Construtor, cria um novo formulário FormCurso */
    public FormCurso(JFrame mdi) {
        this.mdi = mdi;
        initComponents();
    }

    private void atualizaLista() {
        try {
            CursoDAO cursoDAO = new CursoDAO(MDIAcademics.getConexao());
            List<Curso> lista = cursoDAO.listaTodos();
            DefaultTableModel dtm = (DefaultTableModel) this.tbCurso.getModel();
            dtm.setRowCount(0);
            for (Curso curso : lista) {
                dtm.addRow(new Object[]{curso.getCod(), curso.getNome()});
            }
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this.mdi, String.format("Erro ao ler os Cursos:%s", ex.getMessage()), "Erro", JOptionPane.ERROR_MESSAGE);
            Logger.getLogger(FormAvaliacao.class.getName()).log(Level.WARNING, "Erro ao ler os Cursos", ex);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tbCurso = new javax.swing.JTable();
        btSalva = new javax.swing.JButton();
        btLimpa = new javax.swing.JButton();
        btExclui = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        txtCodigo = new javax.swing.JTextField();
        txtNomeCurso = new javax.swing.JTextField();
        btAtualiza = new javax.swing.JButton();

        setClosable(true);
        setTitle("Cadastro de Cursos");
        addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameOpened(evt);
            }
        });

        tbCurso.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Cód.", "Nome"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tbCurso.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tbCursoMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tbCurso);
        tbCurso.getColumnModel().getColumn(0).setMinWidth(40);
        tbCurso.getColumnModel().getColumn(0).setPreferredWidth(40);
        tbCurso.getColumnModel().getColumn(0).setMaxWidth(40);
        tbCurso.getColumnModel().getColumn(1).setResizable(false);

        btSalva.setText("Salvar");
        btSalva.setToolTipText("Salvar registro");
        btSalva.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btSalvaActionPerformed(evt);
            }
        });

        btLimpa.setText("Limpar");
        btLimpa.setToolTipText("Limpar campos");
        btLimpa.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btLimpaActionPerformed(evt);
            }
        });

        btExclui.setText("Excluir");
        btExclui.setToolTipText("Excluir registro");
        btExclui.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btExcluiActionPerformed(evt);
            }
        });

        jLabel1.setText("Cód.:");

        jLabel2.setText("Nome:");

        txtCodigo.setEditable(false);
        txtCodigo.setToolTipText("Código automático");
        txtCodigo.setEnabled(false);

        txtNomeCurso.setToolTipText("Nome do curso");

        btAtualiza.setText("Atualizar");
        btAtualiza.setToolTipText("Atualizar lista de cursos");
        btAtualiza.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btAtualizaActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 516, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(btSalva)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btLimpa)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btExclui)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 275, Short.MAX_VALUE)
                        .addComponent(btAtualiza))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtNomeCurso, javax.swing.GroupLayout.DEFAULT_SIZE, 461, Short.MAX_VALUE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtNomeCurso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 15, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btSalva)
                    .addComponent(btLimpa)
                    .addComponent(btExclui)
                    .addComponent(btAtualiza))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void btSalvaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSalvaActionPerformed
    try {
        Curso curso = new Curso();
        CursoDAO cursoDAO = new CursoDAO(MDIAcademics.getConexao());
        int cod = this.intCampoTelas(this.txtCodigo.getText());
        if (cod > 0) {
            curso.setCod(cod);
            cursoDAO.update(curso);
        } else {
            curso.setNome(this.txtNomeCurso.getText());
            cursoDAO.create(curso);
        }
    } catch (SQLException ex) {
        JOptionPane.showMessageDialog(this.mdi, String.format("Erro ao salvar Curso:%s", ex.getMessage()), "Erro", JOptionPane.ERROR_MESSAGE);
        Logger.getLogger(FormCurso.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NumberFormatException ex) {
        JOptionPane.showMessageDialog(this.mdi, "Número mal formatado [Código]");
        this.txtCodigo.requestFocus();
    }
    this.atualizaLista();
    this.limpaTela();
}//GEN-LAST:event_btSalvaActionPerformed

private void btLimpaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btLimpaActionPerformed
    this.limpaTela();
}//GEN-LAST:event_btLimpaActionPerformed

    private void limpaTela() {
        this.txtCodigo.setText(null);
        this.txtNomeCurso.setText(null);
    }

    private void preencheTela(Curso curso) {
        try {
            CursoDAO cursoDAO = new CursoDAO(MDIAcademics.getConexao());
            curso = cursoDAO.retrieve(curso);
            if (curso != null) {
                this.txtCodigo.setText(Integer.toString(curso.getCod()));
                this.txtNomeCurso.setText(curso.getNome());
            }
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this.mdi, String.format("Não foi possível carregar Cursos: %s", ex.getMessage()), "Erro", JOptionPane.ERROR_MESSAGE);
            Logger.getLogger(FormCurso.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

private void tbCursoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbCursoMouseClicked
    if (evt.getClickCount() > 0) {
        JTable obj = (JTable) evt.getComponent();
        int linha = obj.getSelectedRow();
        Integer cod = (Integer) obj.getModel().getValueAt(linha, 0);
        Curso curso = new Curso(cod);
        this.preencheTela(curso);
    }
}//GEN-LAST:event_tbCursoMouseClicked

private void btExcluiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btExcluiActionPerformed
    try {
        int cod = intCampoTelas(this.txtCodigo.getText());
        if (cod > 0) {
            CursoDAO cursoDAO = new CursoDAO(MDIAcademics.getConexao());
            Curso curso = new Curso(cod);
            cursoDAO.delete(curso);
            this.limpaTela();
            this.atualizaLista();
        }
    } catch (SQLException ex) {
        JOptionPane.showMessageDialog(this.mdi, String.format("Erro ao excluir Curso:%s", ex.getMessage()), "Erro", JOptionPane.ERROR_MESSAGE);
        Logger.getLogger(FormCurso.class.getName()).log(Level.WARNING, "Erro ao excluir Curso", ex);
    }

}//GEN-LAST:event_btExcluiActionPerformed

private void btAtualizaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAtualizaActionPerformed
    this.atualizaLista();
    this.limpaTela();
}//GEN-LAST:event_btAtualizaActionPerformed

private void formInternalFrameOpened(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameOpened
    this.atualizaLista();
}//GEN-LAST:event_formInternalFrameOpened

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btAtualiza;
    private javax.swing.JButton btExclui;
    private javax.swing.JButton btLimpa;
    private javax.swing.JButton btSalva;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tbCurso;
    private javax.swing.JTextField txtCodigo;
    private javax.swing.JTextField txtNomeCurso;
    // End of variables declaration//GEN-END:variables

    private int intCampoTelas(String valor) {
        int ret = 0;
        try {
            ret = Integer.parseInt(valor);
        } catch (NumberFormatException ex) {
        }
        return ret;
    }
}
